package cn.you.GenghisKhan.config.db;
import cn.you.GenghisKhan.common.extension.ExtensionLoader;
import cn.you.GenghisKhan.config.ConfigCentre;
import cn.you.GenghisKhan.db.relation.DynamicDataSource;
import cn.you.GenghisKhan.db.relation.bean.DatabaseBean;
import cn.you.GenghisKhan.db.relation.bean.TenantBean;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.util.*;
public class DataSourceConfig {
    public static List<TenantBean> TENANTBEAN=new ArrayList<>();
    @Bean
    @Primary
    public DynamicDataSource dynamicDataSource() {
        List<TenantBean> tenantBeanList=ExtensionLoader.getExtensionLoader(ConfigCentre.class).getAdaptiveExtension().getTenantBeans();
        DynamicDataSource dataSource = new DynamicDataSource();
        Map<Object, Object> targetDataSourcesMap = new HashMap<>();
        for(TenantBean tenantBean : tenantBeanList)
        {
            DataSource ds=this.initDataSource(tenantBean);
            targetDataSourcesMap.put(tenantBean.getDbTag(),ds);
        }
        dataSource.setTargetDataSources(targetDataSourcesMap);
        if (targetDataSourcesMap.size()==0) {
            throw new IllegalArgumentException("not exists datasource error!");
        }
        DataSource defaultDs=null;
        for (Map.Entry<Object, Object> entry : targetDataSourcesMap.entrySet()) {
            defaultDs= (DataSource)entry.getValue();
            break;
        }
        dataSource.setDefaultTargetDataSource(defaultDs);
        return dataSource;
    }
    private DataSource initDataSource(TenantBean tenantBean ){
        String tag=tenantBean.getDbTag();

        DatabaseBean databaseBean= ExtensionLoader.getExtensionLoader(ConfigCentre.class).getAdaptiveExtension().getDatabaseBean(tag);
        if(databaseBean!=null)
        {
            TENANTBEAN.add(tenantBean);
        }
        DataSource ds=null;
        Properties props = new Properties();
        String jdbcUrl = "";
        String driverClassName="";
        int dbType=databaseBean.getDbType();
        switch (dbType)
        {
            case 1:
                driverClassName="com.mysql.jdbc.Driver";
            jdbcUrl = "jdbc:mysql://"+databaseBean.getHost()+":"+databaseBean.getPort()+"/"+databaseBean.getName()+"?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true";
            break;
            case 2:
                driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
                jdbcUrl = "jdbc:sqlserver://"+databaseBean.getHost()+":"+databaseBean.getPort()+";DatabaseName="+databaseBean.getName();
                break;
            case 3:
                driverClassName="oracle.jdbc.driver.OracleDriver";
                jdbcUrl = "jdbc:oracle:thin:@"+databaseBean.getHost()+":"+databaseBean.getPort()+":"+databaseBean.getName();
                break;
        }
        props.put("driverClassName",driverClassName);
        props.put("url", jdbcUrl);
        props.put("username",databaseBean.getUsername());
        props.put("password",databaseBean.getPassword());
        props.put("initialSize",String.valueOf(databaseBean.getInitialSize()));
        props.put("maxActive",String.valueOf(databaseBean.getMaxActive()));
        props.put("minIdle",String.valueOf(databaseBean.getMinIdle()));
        props.put("maxWait",String.valueOf(databaseBean.getMaxWait()));
        props.put("filters","stat,wall,log4j");
        try {
            ds=  DruidDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return  ds;
    }

}
